<template>
  <el-dialog
    v-el-drag-dialog
    title="新增冲抵单"
    :visible.sync="visible"
    width="1200px"
    top="100px"
    @closed="reset"
  >
    <div class="store-warning">
      <el-form ref="dataForm" class="form" :rules="rules" :model="temp" inline>
        <el-form-item label="责任机构:" prop="orgSNNo">
          <el-tree-select
            v-model="temp.orgSNNo"
            class="tree-select"
            :popover-width="360"
            :clearable="false"
            :select-params="{
              clearable: false,
              placeholder: '请选择',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item label="冲抵责任人:" prop="ownerId">
          <el-select v-model="temp.ownerId" :loading="$loadingPlugin.getOwnersList" placeholder="请选择">
            <el-option
              v-for="item in ownersList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="冲抵时间:" prop="correctDt">
          <el-date-picker
            v-model="temp.correctDt"
            type="datetime"
            placeholder="选择日期时间"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="temp.remark" type="textarea" :rows="1" maxlength="255" style="width: 860px;" />
        </el-form-item>
      </el-form>
      <div class="goods-list">
        <div>
          <el-input v-model.trim="goodsName" placeholder="请输入商品名称" clearable style="width: 200px;" @keydown.native="fetchData">
            <el-button slot="append" class="append-search" @click="fetchData">查询</el-button>
          </el-input>
          <aside-tree
            title="商品分类"
            :mouse-button="false"
            :tree-data="goodsTypeData"
            :loading="$loadingPlugin.getGoodsTypeData"
            @currentChange="currentChange"
            @refresh="getGoodsTypeData"
          />
        </div>
        <div class="table-container">
          <lb-table
            ref="lbTable1"
            v-loading="$loadingPlugin.fetchData"
            border
            element-loading-text="加载中"
            :column="tableData.column"
            :data="tableData.data"
            :height="432"
            :immediate-fetch="false"
            table-key="goodsId"
            @fetch="fetchData"
            @selection-change="handleSelectionChange"
          />
        </div>
        <div class="selected-table">
          <lb-table
            ref="lbTable2"
            border
            :column="selectTableData.column"
            :data="selectTableData.data"
            :height="432"
            table-key="id"
          />
        </div>
      </div>
      <div>
        <p class="tip">* 输入正数表示此次冲抵在原业务数据基础上增加， 输入负数表示此次冲抵在原业务数据基础上减少</p>
        <p class="total">冲抵金额：{{ total }}</p>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AsideTree from '../../../components/GoodsTypeTree'
  import {
    goodsTypeQueryList,
    queryGoodsList,
    querySaveOrderCorrectAdd,
    queryOwnerList, querySpecListAll
  } from '@/api'
  import moment from 'dayjs'
  import { formatColumnMap } from '@/utils'
  import getTreeData from '@/utils/jsonTree'

  export default {
    name: 'add',
    components: {
      AsideTree
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        org: null,
        goodsName: '',
        multipleSelection: [],
        ownersList: [],
        specList: [], // 商品型号列表
        gtId: 0, // 商品类型id
        goodsTypeData: [],
        temp: {
          orgSNNo: '',
          ownerId: '',
          correctDt: '',
          remark: ''
        },
        rules: {
          orgSNNo: [{ required: true, message: '请选择责任机构', trigger: 'change' }],
          ownerId: [{ required: true, message: '请选择责任冲抵人', trigger: 'blur' }],
          correctDt: [{ required: true, message: '请选择冲抵时间', trigger: 'blur' }]
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'selection',
              width: 50
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 200
            },
            {
              prop: 'specCode',
              label: '规格型号',
              width: 80,
              render: (h, { row }) => <span>{ row.specCode && formatColumnMap(this.specList, 'specCode', row.specCode, 'specName') }</span>
            },
            {
              prop: 'unitName',
              label: '单位',
              width: 50
            }
          ],
          data: []
        },
        selectTableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 120
            },
            {
              prop: 'gtName',
              label: '商品类型',
              width: 100
            },
            {
              prop: 'specCode',
              label: '规格型号',
              width: 120,
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit && scope.row.pricingMode === 2
                        ? (
                          <el-select
                            value={scope.row[scope.column.property]}
                            onChange={val => {
                              scope.row[scope.column.property] = val
                            }}
                          >
                            {this.specList.map(option => {
                              return (
                                <el-option
                                  label={option.specName}
                                  value={option.specCode}
                                ></el-option>
                              )
                            })}
                          </el-select>
                        )
                        : <span>{ scope.row.specCode && formatColumnMap(this.specList, 'specCode', scope.row.specCode, 'specName') }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'correctCount',
              width: 100,
              label: '数量',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input-number size='small' controls={false} value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val }} min={-99999} max={99999} precision={0} controls-position='right'></el-input-number>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'correctWeight',
              width: 100,
              label: '重量(kg)',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit && scope.row.pricingMode === 2
                        ? <el-input-number size='small' controls={false} value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val }} min={-99999} max={99999} precision={2} controls-position='right'></el-input-number>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'correctAmount',
              width: 100,
              label: '金额',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input-number size='small' controls={false} value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val }} min={-99999} max={99999} precision={2} controls-position='right'></el-input-number>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              label: '操作',
              width: 80,
              alignt: 'center',
              fixed: 'right',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <div>
                          <el-link underline={false} onClick={ () => { this.handleSave(scope) } }>保存</el-link>
                          <el-link underline={false} type='danger' onClick={ () => { this.handleDel(scope) } }>删除</el-link>
                        </div>
                        : <div>
                          <el-link underline={false} onClick={ () => { this.handleEdit(scope) } }>编辑</el-link>
                          <el-link underline={false} type='danger' onClick={ () => { this.handleDel(scope) } }>删除</el-link>
                        </div>
                    }
                  </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      total: function() {
        let totalAmount = 0
        this.selectTableData.defaultData.forEach(item => {
          if (item.correctAmount) totalAmount += item.correctAmount * 1
        })
        totalAmount = Number(totalAmount || 0).toFixed(2)
        return totalAmount
      }
    },
    created() {
      this.getOwnersList()
    },
    methods: {
      async open(temp) {
        this.getGoodsTypeData()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.org = value
        this.getOwnersList(value.orgId)
        this.$set(this.temp, 'ownerId', '')
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const res = await queryOwnerList({
          orgId: orgId || -1
        })
        this.ownersList = res.data
      },
      // 获取树图数据
      async getGoodsTypeData() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTypeData = getTreeData(data, 'parentId', 'gtId')
      },
      async fetchData() {
        const query = {
          gtId: this.gtId,
          goodsName: this.goodsName,
          currentPage: 1,
          pageSize: 9999
        }
        const res = await queryGoodsList(query)
        this.tableData.data = res.data.rows
        // const copy = JSON.parse(JSON.stringify(this.tableData.data))
        // this.$nextTick(() => {
        //   if (!this.setDefault && this.selectTableData.data.length > 0) {
        //     this.selectTableData.data.forEach(item => {
        //       copy.forEach(it => {
        //         if (it.goodsId === item.goodsId) {
        //           it.stockHighWarn = item.stockHighWarn
        //           it.stockLowWarn = item.stockLowWarn
        //           it.fillCount = item.fillCount
        //         }
        //       })
        //       this.$set(this.tableData, 'data', copy)
        //     })
        //   }
        // })
      },
      // 选择变化
      currentChange(current) {
        this.gtId = current.gtId
        this.fetchData()
        this.getSpecName(current.gtId)
      },
      async getSpecName(gtId) {
        const res = await querySpecListAll({ gtId, currentPage: 1, pageSize: 9999 })
        this.specList = res.data.rows
      },
      // 勾选商品
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.$set(this.selectTableData, 'defaultData', JSON.parse(JSON.stringify(val)))
        this.$set(this.selectTableData, 'data', JSON.parse(JSON.stringify(val)))
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        if (!scope.row.correctAmount) {
          this.$message.warning(`请填写金额`)
          return
        }
        this.$set(scope.row, '_edit', false)
        this.$set(this.selectTableData.defaultData, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      handleDel(scope) {
        this.selectTableData.data.splice(scope.$index, 1)
        this.$refs.lbTable1.toggleRowSelection(scope.row)
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (this.selectTableData.data.length === 0) {
            this.$message.error('请添加商品')
            return
          }
          if (this.selectTableData.data.some(item => !item.correctAmount)) {
            this.$message.error('信息不完整，请填写')
            return
          }
          const copy = JSON.parse(JSON.stringify(this.selectTableData.data))
          copy.forEach(item => {
            item._edit = false
          })
          this.$set(this.selectTableData, 'data', copy)
          const user = this.ownersList.find(item => item.userId === this.temp.ownerId)
          const params = {
            orgName: this.org.orgName,
            orgSNNo: this.org.orgSNNo,
            orgId: this.org.orgId,
            ownerId: this.owner.userId,
            owner: user.userName,
            correctDt: moment(this.temp.correctDt).format(),
            remark: this.temp.remark,
            detailList: this.selectTableData.data
          }
          this.sumbit(params)
        })
      },
      async sumbit(params) {
        await querySaveOrderCorrectAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.multipleSelection = []
        this.tableData.data = []
        this.selectTableData.data = []
        this.selectTableData.defaultData = []
      }
    }
  }
</script>

<style lang="scss" scoped>
.store-warning {
  height: 600px;
  .goods-list {
    display: flex;
    height: 450px;
    margin-top: 5px;
    .table-container {
      width: 380px;
    }
    .selected-table {
      margin-left: 10px;
      overflow: auto;
      flex: 1;
      /deep/ .el-input-number.is-without-controls .el-input__inner {
        width: 80px;
        padding-right: 5px;
        padding-left: 5px;
      }
    }
  }
  .tip {
    color: $dangerColor;
  }
  .total {
    margin-top: 10px;
    font-size: 18px;
    font-weight: 600;
    color: $dangerColor;
  }
  .aside.open {
    width: 200px;
    height: 400px;
  }
}
</style>
